import api from '../../api';
import { PAGINATION } from '../../../constants/common';
import { apiModeUtils } from '../../apiConfig';
import type { Menu } from '../../../types/rbac';

/**
 * 菜单列表查询参数（对应后端SysMenuQuery）
 */
export interface MenuListParams {
  current?: number;
  size?: number;
  code?: string;
  name?: string;
  type?: number; // 1-目录，2-菜单，3-按钮
  status?: number; // 1-启用，0-禁用
  parentId?: number;
  keyword?: string;
  orderBy?: string;
  orderType?: 'asc' | 'desc';
}

/**
 * 创建菜单请求参数（对应后端SysMenuDto）
 */
export interface CreateMenuRequest {
  code: string;
  name: string;
  permissions?: string;
  parentId?: string;
  type: number; // 1-目录，2-菜单，3-按钮
  icon?: string;
  path?: string;
  status?: number; // 1-启用，0-禁用
  description?: string;
  sort?: number;
}

/**
 * 更新菜单请求参数（对应后端SysMenuDto）
 */
export interface UpdateMenuRequest {
  id?: string;
  code?: string;
  name?: string;
  permissions?: string;
  parentId?: string;
  type?: number;
  icon?: string;
  path?: string;
  status?: number;
  description?: string;
  sort?: number;
}

/**
 * 菜单列表响应类型（对应后端分页响应）
 */
export interface MenuListResponse {
  records: Menu[];
  total: number;
  size: number;
  current: number;
  pages: number;
  hasPrevious: boolean;
  hasNext: boolean;
}

/**
 * 移动菜单请求参数
 */
export interface MoveMenuRequest {
  menuId: string;
  targetParentId?: string;
  targetSort?: number;
}

/**
 * 批量操作菜单请求参数
 */
export interface BatchMenuRequest {
  menuIds: string[];
  action: 'enable' | 'disable' | 'delete';
}

/**
 * 菜单统计信息
 */
export interface MenuStats {
  totalMenus: number;
  enabledMenus: number;
  disabledMenus: number;
  menusByType: Array<{
    type: number;
    typeName: string;
    count: number;
  }>;
}

/**
 * 菜单编码检查结果
 */
export interface MenuCodeCheckResult {
  exists: boolean;
}

// 创建API实例
const api_menu = apiModeUtils.createApi('menuApi', api, false);

export const menuApi = {
  /**
   * 分页查询菜单列表
   */
  getMenus: async (params?: MenuListParams): Promise<MenuListResponse> => {
    return api_menu.get('getMenus', '/system/api/v3/sys/menus', {
      params: { ...PAGINATION, ...params }
    });
  },

  /**
   * 获取所有菜单（不分页）
   */
  getAllMenus: (): Promise<Menu[]> => {
    return api_menu.get('getAllMenus', '/system/api/v3/sys/menus/all');
  },

  /**
   * 获取菜单树
   */
  getMenuTree: (type?: number, status?: number): Promise<Menu[]> => {
    return api_menu.get('getMenuTree', '/system/api/v3/sys/menus/tree', {
      params: { type, status }
    });
  },

  /**
   * 根据ID获取菜单详情
   */
  getMenu: (id: string): Promise<Menu> => {
    return api_menu.get('getMenu', `/system/api/v3/sys/menus/${id}`);
  },

  /**
   * 创建菜单
   */
  createMenu: (data: CreateMenuRequest): Promise<Menu> => {
    return api_menu.post('createMenu', '/system/api/v3/sys/menus', data);
  },

  /**
   * 更新菜单
   */
  updateMenu: (data: UpdateMenuRequest): Promise<Menu> => {
    return api_menu.put('updateMenu', `/system/api/v3/sys/menus/${data.id}`, data);
  },

  /**
   * 删除菜单
   */
  deleteMenu: (id: string): Promise<void> => {
    return api_menu.delete('deleteMenu', `/system/api/v3/sys/menus/${id}`);
  },

  /**
   * 批量删除菜单
   */
  batchDeleteMenus: (ids: string[]): Promise<void> => {
    return api_menu.delete('batchDeleteMenus', '/system/api/v3/sys/menus/batch', {
      data: ids
    });
  },

  /**
   * 根据编码获取菜单
   */
  getMenuByCode: (code: string): Promise<Menu> => {
    return api_menu.get('getMenuByCode', `/system/api/v3/sys/menus/code/${code}`);
  },

  /**
   * 获取用户菜单
   */
  getUserMenus: (userId: string): Promise<Menu[]> => {
    return api_menu.get('getUserMenus', `/system/api/v3/sys/menus/user/${userId}`);
  },

  /**
   * 获取角色菜单
   */
  getRoleMenus: (roleId: string): Promise<Menu[]> => {
    return api_menu.get('getRoleMenus', `/system/api/v3/sys/menus/role/${roleId}`);
  },

  /**
   * 获取子菜单
   */
  getChildMenus: (parentId: string): Promise<Menu[]> => {
    return api_menu.get('getChildMenus', `/system/api/v3/sys/menus/${parentId}/children`);
  },

  /**
   * 获取菜单关联角色
   */
  getMenuRoles: (menuId: string): Promise<any[]> => {
    return api_menu.get('getMenuRoles', `/system/api/v3/sys/menus/${menuId}/roles`);
  },

  /**
   * 启用菜单
   */
  enableMenu: (id: string): Promise<void> => {
    return api_menu.put('enableMenu', `/system/api/v3/sys/menus/${id}/enable`);
  },

  /**
   * 禁用菜单
   */
  disableMenu: (id: string): Promise<void> => {
    return api_menu.put('disableMenu', `/system/api/v3/sys/menus/${id}/disable`);
  },

  /**
   * 移动菜单
   */
  moveMenu: (data: MoveMenuRequest): Promise<void> => {
    return api_menu.put('moveMenu', '/system/api/v3/sys/menus/move', data);
  },

  /**
   * 批量更新菜单排序
   */
  batchUpdateSort: (menus: UpdateMenuRequest[]): Promise<void> => {
    return api_menu.put('batchUpdateSort', '/system/api/v3/sys/menus/batch-sort', menus);
  },

  /**
   * 检查菜单编码是否存在
   */
  checkMenuCode: (code: string, excludeId?: string): Promise<MenuCodeCheckResult> => {
    return api_menu.get('checkMenuCode', '/system/api/v3/sys/menus/check-code', {
      params: { code, excludeId }
    });
  },

  /**
   * 切换菜单状态
   */
  toggleMenuStatus: (id: string, status: number): Promise<void> => {
    return status === 1 ? menuApi.enableMenu(id) : menuApi.disableMenu(id);
  },

  /**
   * 批量操作菜单
   */
  batchUpdateMenus: (data: BatchMenuRequest): Promise<void> => {
    const { menuIds, action } = data;
    switch (action) {
      case 'enable':
        return Promise.all(menuIds.map(id => menuApi.enableMenu(id))).then(() => {});
      case 'disable':
        return Promise.all(menuIds.map(id => menuApi.disableMenu(id))).then(() => {});
      case 'delete':
        return menuApi.batchDeleteMenus(menuIds);
      default:
        return Promise.reject(new Error('不支持的操作类型'));
    }
  },

  /**
   * 获取菜单统计信息
   */
  getMenuStats: (): Promise<MenuStats> => {
    return api_menu.get('getMenuStats', '/system/api/v3/sys/menus/stats');
  }
};